<template>
  <div class="app">
    <div class="search-bar">
      <el-form :model="searchData" label-width="100px" style="padding: 0 20px;">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="规则名称" style="margin-bottom: 5px;">
              <el-input v-model="searchData.ruleName" size="medium" class="select-item"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="主指标ID" style="margin-bottom: 5px;">
              <el-input v-model="searchData.masterIndexId" size="medium" class="select-item"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="预警处理方式" style="margin-bottom: 5px;">
              <el-select v-model="searchData.alertHandleType" size="medium" class="select-item">
                  <el-option
                    v-for="item in alertHandleTypeOption"
                    :key="item.index"
                    :label="item.label"
                    :value="item.code">
                  </el-option>
                </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <div style="margin-top: 3px; display: flex; justify-content: center">
              <el-button icon="el-icon-search" type="primary" size="small" @click="handleSearch">查询</el-button>
              <el-button icon="el-icon-refresh-left" size="small" @click="handleClear">重置</el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="add-form">
      <el-button icon="el-icon-plus" v-show="tableOption.isShowOperate" type="primary" size="medium" @click="handleAdd">新增</el-button>
    </div>
    <div ref="ref" :class="tableOption.isShowOperate?'table-box':'table-box2'">
      <TableComponent :columns="tableColumns" :height="height" :data="tableData" @change="onTableChange" :tableOption="tableOption" :page-option="searchData.page" :stripe="stripe" :total="total">
        <template slot-scope="scope">
          <el-button @click="editRow(scope.scope.row)" type="text" size="mini">编辑</el-button>
        </template>
      </TableComponent>
    </div>
    <el-dialog :title="title" :visible.sync="dialogVisibleAdd" width="80%" :before-close="handleCancle">
      <div class="dialog-box">
        <el-form ref="form" :model="addForm" label-width="110px" :rules="rules" label-position="left" style="padding: 0 20px;">
          <el-row :gutter="30">
            <el-col :span="12">
              <el-form-item label="规则名称" prop="ruleName" style="margin-bottom: 16px;">
                <el-input v-model="addForm.ruleName" size="medium"></el-input>
              </el-form-item>
              <el-form-item label="主指标ID" prop="masterIndexId" style="margin-bottom: 16px;">
                <el-select v-model="addForm.masterIndexId" size="medium" class="select-item">
                  <el-option
                    v-for="item in masterIndexIdOption || []"
                    :key="item.index"
                    :label="item.indexName"
                    :value="item.indexId">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="副指标类型" prop="slaverIndexType" style="margin-bottom: 16px;">
                <el-select v-model="addForm.slaverIndexType" size="medium" class="select-item" @change="selectChange">
                  <el-option
                    v-for="item in slaverIndexTypeOption"
                    :key="item.index"
                    :label="item.label"
                    :value="item.code">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="计算方式" prop="calculateType" style="margin-bottom: 16px;">
                <el-select v-model="addForm.calculateType" size="medium" class="select-item">
                  <el-option
                    v-for="item in calculateOption"
                    :key="item.index"
                    :label="item.label"
                    :value="item.code">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="规则内容描述" prop="ruleDes" style="margin-bottom: 16px;">
                <el-input v-model="addForm.ruleDes" size="medium"></el-input>
              </el-form-item>
              <el-form-item label="预警处理方式" prop="alertHandleType" style="margin-bottom: 16px;">
                <el-select v-model="addForm.alertHandleType" size="medium" class="select-item">
                  <el-option
                    v-for="item in alertHandleTypeOption"
                    :key="item.index"
                    :label="item.label"
                    :value="item.code">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="副指标值" prop="slaverIndexValue" style="margin-bottom: 16px;">
                <el-input v-if="isInput" v-model="addForm.slaverIndexValue" size="medium"></el-input>
                <el-select v-if="!isInput" v-model="addForm.masterIndexId" size="medium" class="select-item">
                  <el-option
                    v-for="item in masterIndexIdOption || []"
                    :key="item.index"
                    :label="item.indexName"
                    :value="item.indexId">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item :label="changeCompanyName" style="margin-bottom: 16px; margin-left: 8px" prop="applicableCompany">
                <el-select v-model="addForm.applicableCompany"
                  size="medium"
                  clearable
                  multiple
                  filterable
                  :filter-method="filterMethod"
                  @visible-change="visibleChange"
                  v-el-select-loadmore="loadMore(rangeNumber)"
                  style="margin-left: -8px; width: calc(100% - 22px)"
                  placeholder="请选择公司">
                  <el-option
                    v-for="item in options.slice(0, rangeNumber)"
                    :key="item.code"
                    :label="item.value"
                    :value="item.code">
                  </el-option>
                </el-select>
                <el-button type="text" size="mini" @click="handleChangeCompanyType">切换</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <span slot="footer">
        <el-button @click="handleCancle">取 消</el-button>
        <el-button type="primary" @click="handleSubmit('form')">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import TableComponent from '@/components/Table/table'
import { queryRuleSetting, addRuleSetting, querySingleRuleSetting, editRuleSetting, queryTargtDefine, queryAllCompanyList } from '@/api/modules/warning.js'
import { tableColumns, calculateOption, slaverIndexTypeOption, alertHandleTypeOption } from './index.js'
import { _debounce } from './index.js'
export default {
  components: {
    TableComponent
  },
  data() {
    return {
      searchData: {
        alertHandleType: '',
        masterIndexId: '',
        ruleName: '',
        page: {
          pageNum: 1,
          pageSize: 10
        }
      },
      calculateOption,
      slaverIndexTypeOption,
      alertHandleTypeOption,
      tableColumns,
      tableData: [],
      height: null,
      title: '',
      total: 0,
      tableOption: {
        isShowOperate: true,
        operateWidth: '100px'
      },
      stripe: true,
      dialogVisibleAdd: false,
      addForm: {
        ruleName: '',
        ruleDes: '',
        masterIndexId: '',
        calculateType: '',
        applicableCompany: [],
        companyType: '0',
        slaverIndexType: '',
        slaverIndexValue: '',
        alertHandleType: ''
      },
      companyNameOption: [],
      masterIndexIdOption: [],
      options: [],
      rangeNumber: 10,
      rules: {
        ruleName: [{ required: true, message: '请输入规则名称', trigger: 'change' }],
        ruleDes: [{ required: true, message: '请输入规则内容描述', trigger: 'change' }],
        masterIndexId: [{ required: true, message: '请输入主指标ID', trigger: 'change' }],
        calculateType: [{ required: true, message: '请选择计算方式', trigger: 'change' }],
        slaverIndexType: [{ required: true, message: '请选择副指标类型', trigger: 'change' }],
        slaverIndexValue: [{ required: true, message: '请输入副指标值', trigger: 'change' }],
        alertHandleType: [{ required: true, message: '请选择预警处理方式', trigger: 'change' }],
      },
      saveRuleCode: {
        ruleId: ''
      },
      changeCompanyName: '适用公司',
      isInput: true
    }
  },
  mounted() {
    const key = this.$store.state.key.resourceCode
    if (key === '0') {
      this.tableOption.isShowOperate = false
    } else {
      this.tableOption.isShowOperate = true
    }
    this.$nextTick(() => {
      this.height = this.$refs.ref.offsetHeight
    })
    window.onresize = () => {
      this.height = this.$refs.ref.offsetHeight
    }
    this.initData(this.searchData)
    // 白名单公司查询
    queryAllCompanyList({ type: '1', code: '', chiName: '' }).then(res => {
      if (res.data.code === '0') {
        const obj = { value: '全集团', code: '00' }
        const arr = res.data.body
        arr.unshift(obj)
        this.companyNameOption = arr
      }
    })
  },
  destroyed(){
    window.onresize = null
  },
  directives:{
    'el-select-loadmore':(el, binding) => {
      // 获取element-ui定义好的scroll盒子
      const SELECTWRAP_DOM = el.querySelector(".el-select-dropdown .el-select-dropdown__wrap")
      if(SELECTWRAP_DOM){
        SELECTWRAP_DOM.addEventListener("scroll", function () {
          /**
           * scrollHeight 获取元素内容高度(只读)
           * scrollTop 获取或者设置元素的偏移值,
           *  常用于:计算滚动条的位置, 当一个元素的容器没有产生垂直方向的滚动条, 那它的scrollTop的值默认为0.
           * clientHeight 读取元素的可见高度(只读)
           * 如果元素滚动到底, 下面等式返回true, 没有则返回false:
           * ele.scrollHeight - ele.scrollTop === ele.clientHeight;
           */
          const condition = this.scrollHeight - this.scrollTop <= this.clientHeight
          if (condition) binding.value()
        })
      }
    }
  },
  methods: {
    initData(params) {
      queryRuleSetting(params).then(res => {
        if (res.data.code === '200') {
          this.tableData = res.data.data.list
          this.total = res.data.data.total
        }
      })
    },
    initSelect() {
      const data = {
        indexName: '',
        indexType: '',
        calculateFreq: ''
      }
      queryTargtDefine(data).then(res => {
        this.masterIndexIdOption = res.data.data.list
      })
    },
    handleChangeCompanyType() {
      if (this.changeCompanyName == '适用公司') {
        this.changeCompanyName = '不适用公司'
        this.addForm.companyType = '1'
      } else {
        this.changeCompanyName = '适用公司'
        this.addForm.companyType = '0'
      }
    },
    selectChange(val) {
      if (val === '1') {
        this.isInput = false
      } else {
        this.isInput = true
      }
    },
    // 点击查询
    handleSearch() {
      this.initData(this.searchData)
    },
    // 点击新增
    handleAdd() {
      this.dialogVisibleAdd = true
      this.title = '新增'
      this.addForm.companyType = '0'
      this.changeCompanyName = '适用公司'
      this.initSelect()
    },
    // 筛选方法
    filterMethod:_debounce(function(filterVal) {
      if(filterVal){
        let filterArr = this.companyNameOption.filter((item) => {
          return item.value.toLowerCase().includes(filterVal.toLowerCase())
        })
        this.options = filterArr
      }else{
        this.options = this.companyNameOption
      }
    }),
    // 下拉框出现时，调用过滤方法
    visibleChange(flag){
      if(flag){
        this.filterMethod()
      }
    },
    loadMore(n) {
      // n是默认初始展示的条数会在渲染的时候就可以获取,具体可以打log查看
      // elementui下拉超过7条才会出滚动条,如果初始不出滚动条无法触发loadMore方法
      return () => (this.rangeNumber += 5) // 每次滚动到底部可以新增条数  可自定义
    },
    // 点击确定新增/修改
    handleSubmit(formName) {
      if (this.title === '新增') {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            addRuleSetting(this.addForm).then(res => {
              if (res.data.code === '200') {
                this.resetForm('form')
                this.dialogVisibleAdd = false
                this.$message.success('新增成功')
                this.initData(this.searchData)
              } else {
                this.$message.error(res.data.message)
              }
            })
          } else {
            return false
          }
        })
      } else if (this.title === '修改') {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            const params = Object.assign(this.addForm, this.saveRuleCode)
            editRuleSetting(params).then(res => {
              if (res.data.code === '200') {
                this.resetForm('form')
                this.dialogVisibleAdd = false
                this.$message.success('修改成功')
                this.initData(this.searchData)
              } else {
                this.$message.error(res.data.message)
              }
            })
          } else {
            return false
          }
        })
      }
      
    },
    editRow(row) {
      this.filterMethod()
      this.saveRuleCode.ruleId = row.ruleId
      this.dialogVisibleAdd = true
      this.title = '修改'
      this.initSelect()
      const params = {
        ruleId: row.ruleId
      }
      querySingleRuleSetting(params).then(res => {
        if (res.data.code === '200') {
          this.addForm = res.data.data
          if (res.data.data.companyType === '0') {
            this.changeCompanyName = '适用公司'
          } else if (res.data.data.companyType === '1') {
            this.changeCompanyName = '不适用公司'
          }
          this.selectChange(res.data.data.slaverIndexType)
          const str = res.data.data.applicableCompany
          const arr = str.split(',')
          this.addForm.applicableCompany = arr
        }
      })
    },
    // 分页
    onTableChange(val) {
      this.searchData.page = val
      this.initData(this.searchData)
    },
    
    handleClear() {
      this.searchData.ruleName = ''
      this.searchData.masterIndexId = ''
      this.searchData.alertHandleType = ''
    },
    handleCancle() {
      this.resetForm('form')
      this.dialogVisibleAdd = false
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    }
  }
}
</script>

<style lang="less" scoped>
  .app {
    height: 100%;
    .search-bar {
      width: calc(100% - 60px);
      background-color: #ffffff;
      margin-bottom: 10px;
      padding: 10px 30px;
    }
    .add-form {
      padding: 10px 20px;
      background-color: #ffffff;
    }
    .table-box {
      width: 100%;
      height: calc(100vh - 260px);
      .table {
        height: 100%;
      }
    }
    .table-box2 {
      width: 100%;
      height: calc(100vh - 228px);
      .table {
        height: 100%;
      }
    }
    .select-item {
      width: 100%;
    }
  }
</style>
